package common;

import java.util.Arrays;

/**
 *
 * @author jack.wu
 * @since 2019/9/10
 */
public class SortForkJoin {

    public static int[] sort(int[] array) {
        if (array.length == 0) {
            return array;
        }
        for (int i = 0; i < array.length - 1; i++) {
            int preIndex = i;
            int currentValue = array[i + 1];
            while (preIndex >= 0 && array[preIndex] > currentValue) {
                array[preIndex + 1] = array[preIndex];
                preIndex--;
            }
            array[preIndex + 1] = currentValue;
        }
        return array;
    }

    /**
     * 组合
     *
     * @param left
     * @param right
     * @return
     */
    public static int[] merge(int[] left, int[] right) {
        int[] result = new int[left.length + right.length];
        for (int resultIndex = 0, leftIndex = 0, rightIndex = 0; resultIndex < result.length; resultIndex++) {
            if (leftIndex >= left.length) {
                result[resultIndex] = right[rightIndex++];
            } else if (rightIndex >= right.length) {
                result[resultIndex] = left[leftIndex++];
            } else if (left[leftIndex] > right[rightIndex]) {
                result[resultIndex] = right[rightIndex++];
            } else {
                result[resultIndex] = left[leftIndex++];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] array1 = {1,0,7};
        int[] array2 = {4,5,6};
        int[] merge = merge(array1, array2);
        System.out.println(Arrays.toString(merge));
    }
}
